'use strict';

const { USER_NOT_EXISTS } = require('../constant');
const { getPagination } = require('../tools');

const Service = require('egg').Service;

class UserService extends Service {
  async list({ page_num, page_size }) {
    const { offset, limit } = getPagination(page_num, page_size);

    try {
      const res = await this.ctx.model.User.findAndCountAll({
        offset,
        limit,
        attributes: {
          exclude: ['password'],
        },
      });
      return {
        page_num: +page_num,
        page_size: +page_size,
        ...res,
      };
    } catch (error) {
      return {
        isErr: true,
        error,
      };
    }
  }

  async find(id) {
    // 根据ID查询用户
    try {
      const res = await this.ctx.model.User.findByPk(id, {
        attributes: {
          exclude: ['password'],
        },
      });
      if (!res) {
        return {
          isErr: true,
          error: { msg: USER_NOT_EXISTS },
        };
      }
      return res;
    } catch (error) {
      return {
        isErr: true,
        error,
      };
    }
  }

  async create(data) {
    // 创建用户
    try {
      const result = await this.ctx.model.User.create(data);

      const { password, ...create } = result.dataValues;

      return create;
    } catch (error) {
      return {
        isErr: true,
        error,
      };
    }
  }

  async update(id, data) {
    // 更新用户
    const user = await this.ctx.model.User.findByPk(id);
    if (!user) return null;
    return await user.update(data);
  }

  async delete(id) {
    // 删除用户
    const user = await this.ctx.model.User.findByPk(id);
    if (!user) return null;
    return await user.destroy();
  }
}

module.exports = UserService;
